// 注入脚本到页面上下文中拦截WebSocket
console.log('[Content] 开始注入WebSocket拦截脚本');

const script = document.createElement('script');
script.src = chrome.runtime.getURL('inject.js');
script.onload = function() {
  console.log('[Content] 注入脚本加载完成');
  this.remove();
};
(document.head || document.documentElement).appendChild(script);

// 检查插件上下文是否有效
function isExtensionContextValid() {
  try {
    return chrome.runtime && chrome.runtime.id;
  } catch (e) {
    return false;
  }
}

// 安全发送消息
function safeSendMessage(message) {
  if (!isExtensionContextValid()) {
    console.log('[Content] 插件上下文已失效，跳过消息发送');
    return;
  }
  
  try {
    chrome.runtime.sendMessage(message).catch(error => {
      if (error.message.includes('Extension context invalidated')) {
        console.log('[Content] 插件上下文失效，停止发送消息');
      }
    });
  } catch (error) {
    console.log('[Content] 发送消息失败:', error.message);
  }
}

// 监听来自注入脚本的消息
window.addEventListener('message', function(event) {
  if (event.source !== window) return;
  
  if (event.data.type === 'WEBSOCKET_DATA') {
    console.log('[Content] 收到WebSocket数据:', event.data);
    
    const parsedMessage = xtermController.handleMessageData(event.data.data);
    
    safeSendMessage({
      type: 'WEBSOCKET_DATA',
      data: {
        url: event.data.url,
        message: parsedMessage,
        timestamp: event.data.timestamp
      }
    });
  }
  
  if (event.data.type === 'WEBSOCKET_SEND') {
    console.log('[Content] 收到WebSocket发送:', event.data);
    
    safeSendMessage({
      type: 'WEBSOCKET_SEND',
      data: {
        url: event.data.url,
        message: typeof event.data.data === 'string' ? event.data.data : '[Binary]',
        timestamp: event.data.timestamp
      }
    });
  }
});

class XTermController {
  constructor() {
    this.terminals = new Map();
    this.commandQueue = [];
    this.isProcessing = false;
    this.interceptedSockets = new Map();
    this.init();
  }

  init() {
    // WebSocket拦截已在文件开头立即执行
    this.interceptXTerm();
    
    // 等待DOM准备好后再进行DOM相关操作
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.initDOMOperations();
      });
    } else {
      this.initDOMOperations();
    }
    
    this.setupMessageListener();
    this.checkInterceptionStatus();
  }
  
  initDOMOperations() {
    console.log('[Content] DOM准备完成，开始DOM相关操作');
    this.detectTerminals();
    this.setupMutationObserver();
  }

  detectTerminals() {
    // 只检测真正的xterm终端容器
    const candidates = new Set();
    
    // 查找包含xterm-screen的元素（这是真正的终端）
    document.querySelectorAll('.xterm').forEach(el => {
      if (this.isValidTerminal(el)) {
        candidates.add(el);
      }
    });
    
    console.log(`[Content] 检测到 ${candidates.size} 个候选终端`);
    candidates.forEach(el => this.registerTerminal(el));
  }

  isValidTerminal(element) {
    // 检查是否是有效的终端元素
    if (!element || element.offsetWidth === 0 || element.offsetHeight === 0) {
      return false;
    }
    
    // 检查是否已经被注册过
    const existingId = element.dataset.xtermControllerId;
    if (existingId && this.terminals.has(existingId)) {
      console.log('[Content] 终端已注册，跳过:', existingId);
      return false;
    }
    
    // 必须包含xterm-screen子元素才是真正的终端
    const hasXTermScreen = element.querySelector('.xterm-screen');
    if (!hasXTermScreen) {
      console.log('[Content] 元素缺少xterm-screen，跳过');
      return false;
    }
    
    // 检查是否是顶层终端容器（避免检测到子元素）
    const isTopLevel = !element.closest('.xterm')?.querySelector('.xterm-screen') || 
                      element.closest('.xterm') === element;
    
    if (!isTopLevel) {
      console.log('[Content] 不是顶层终端容器，跳过');
      return false;
    }
    
    console.log('[Content] 发现有效终端:', element.className);
    return true;
  }

  registerTerminal(element) {
    // 检查是否已经有相同的终端元素
    for (let [id, terminal] of this.terminals) {
      if (terminal.element === element) {
        console.log(`[Content] 终端元素已存在: ${id}`);
        return;
      }
    }
    
    const terminalId = this.generateTerminalId(element);
    
    // 标记元素避免重复检测
    element.dataset.xtermControllerId = terminalId;
    
    const terminal = {
      id: terminalId,
      element: element,
      instance: this.getXTermInstance(element),
      lastOutput: '',
      commandHistory: []
    };
    
    this.terminals.set(terminalId, terminal);
    console.log(`[Content] 注册新终端: ${terminalId}`);
    console.log(`[Content] 当前终端总数: ${this.terminals.size}`);
    
    // 监听终端输出
    this.monitorTerminalOutput(terminal);
  }

  /**
   * 获取xterm实例 - 专门用于发送命令
   * 这个方法查找页面中真实的xterm.js实例，用于直接调用write()方法发送命令
   * 与WebSocket拦截功能完全独立，不会相互影响
   * 
   * @param {Element} element - 终端DOM元素
   * @returns {Object|null} xterm实例对象，包含write()方法用于发送命令
   */
  getXTermInstance(element) {
    console.log('[Content] 开始查找xterm实例用于发送命令');
    
    // 在元素及其属性中查找xterm实例
    // 这些是常见的xterm实例存储属性名
    const possibleKeys = ['_xterm', 'terminal', '__xterm', 'xterm', '_terminal', 'xtermjs', 'term'];
    
    // 首先在当前元素上查找
    for (let key of possibleKeys) {
      if (element[key]) {
        console.log(`[Content] 在元素上找到xterm实例: ${key}`);
        return element[key];
      }
    }
    
    // 然后在子元素上查找
    const children = element.querySelectorAll('*');
    for (let child of children) {
      for (let key of possibleKeys) {
        if (child[key] && typeof child[key] === 'object') {
          // 验证是否为有效的xterm实例（必须有write或buffer方法）
          if (child[key].write || child[key].buffer) {
            console.log(`[Content] 在子元素上找到xterm实例: ${key}`);
            return child[key];
          }
        }
      }
    }
    
    console.log('[Content] 未找到xterm实例');
    return null;
  }

  monitorTerminalOutput(terminal) {
    console.log('[Content] 使用DOM监听方式，不依赖xterm实例');
    // 直接使用DOM监听，避免与拦截系统冲突
    this.fallbackDOMMonitor(terminal);
  }

  async sendCommand(terminalId, command) {
    const terminal = this.terminals.get(terminalId);
    if (!terminal) {
      console.error(`终端 ${terminalId} 不存在，当前终端:`, Array.from(this.terminals.keys()));
      // 尝试使用第一个可用终端
      const firstTerminal = this.terminals.values().next().value;
      if (firstTerminal) {
        console.log(`使用第一个可用终端: ${firstTerminal.id}`);
        return this.sendCommand(firstTerminal.id, command);
      }
      return false;
    }

    console.log(`[Content] 尝试发送命令到 ${terminalId}: ${command}`);
    console.log('[Content] 终端实例:', terminal.instance);
    console.log('[Content] 终端元素:', terminal.element);

    try {
      let success = false;
      
      // 方法1: 使用xterm实例
      if (terminal.instance && terminal.instance.write) {
        console.log('使用xterm实例发送命令');
        terminal.instance.write(command + '\r');
        success = true;
      }
      // 方法2: 查找输入框
      else if (await this.tryInputMethod(terminal.element, command)) {
        console.log('使用输入框方法发送命令');
        success = true;
      }
      // 方法3: 模拟键盘输入
      else {
        console.log('使用键盘模拟发送命令');
        this.simulateKeyboardInput(terminal.element, command);
        success = true;
      }
      
      if (success) {
        terminal.commandHistory.push({
          command: command,
          timestamp: Date.now()
        });
      }
      
      console.log(`命令发送${success ? '成功' : '失败'}: ${command}`);
      return success;
    } catch (error) {
      console.error(`发送命令失败:`, error);
      return false;
    }
  }

  async tryInputMethod(element, command) {
    // 优先查找xterm的输入框
    console.log('[Content] 开始查找输入框');
    const xtermInput = element.querySelector('textarea.xterm-helper-textarea');
    console.log('[Content] 查找结果:', xtermInput);
    
    if (xtermInput) {
      console.log('[Content] 找到xterm输入框');
      try {
        xtermInput.focus();
        
        // 模拟键盘输入，每个字符间加延迟
        for (let i = 0; i < command.length; i++) {
          const char = command[i];
          console.log(`[Content] 发送字符: '${char}' (${char.charCodeAt(0)})`);
          if (char === ' ') {
            console.log('[Content] 检测到空格字符');
          }
          
          // 使用更精确的keyCode映射
          let keyCode;
          if (char >= 'a' && char <= 'z') {
            keyCode = char.toUpperCase().charCodeAt(0);
          } else if (char === '-') {
            keyCode = 189; // 标准的减号键码
          } else if (char === ' ') {
            keyCode = 32; // 空格键码
            console.log('[Content] 设置空格 keyCode: 32');
          } else {
            keyCode = char.charCodeAt(0);
          }
          
          // 发送keydown事件
          const keydownEvent = new KeyboardEvent('keydown', {
            key: char,
            code: this.getKeyCode(char),
            keyCode: keyCode,
            charCode: char.charCodeAt(0),
            bubbles: true,
            cancelable: true
          });
          
          console.log(`[Content] 事件详情:`, {
            key: keydownEvent.key,
            code: keydownEvent.code,
            keyCode: keydownEvent.keyCode,
            charCode: keydownEvent.charCode
          });
          
          xtermInput.dispatchEvent(keydownEvent);
          
          // 只对空格发送keypress事件
          if (char === ' ') {
            const keypressEvent = new KeyboardEvent('keypress', {
              key: char,
              keyCode: keyCode,
              charCode: char.charCodeAt(0),
              bubbles: true,
              cancelable: true
            });
            xtermInput.dispatchEvent(keypressEvent);
          }
          // 每个字符间延迟20ms
          await new Promise(resolve => setTimeout(resolve, 20));
        }
        
        // 发送回车前稍微延迟
        await new Promise(resolve => setTimeout(resolve, 20));
        xtermInput.dispatchEvent(new KeyboardEvent('keydown', {
          key: 'Enter',
          keyCode: 13,
          charCode: 13,
          bubbles: true,
          cancelable: true
        }));
        return true;
      } catch (e) {
        console.log('[Content] xterm输入框操作失败:', e);
      }
    } else {
      console.log('[Content] 未找到xterm输入框，尝试查找其他输入框');
      // 显示所有可能的textarea
      const allTextareas = element.querySelectorAll('textarea');
      console.log('[Content] 找到的所有textarea:', allTextareas);
      allTextareas.forEach((ta, index) => {
        console.log(`[Content] textarea ${index}:`, ta.className, ta.id);
      });
    }
    
    // 备用方案：查找其他输入框
    const inputs = [
      element.querySelector('input'),
      element.querySelector('textarea'),
      element.querySelector('[contenteditable="true"]')
    ].filter(Boolean);
    
    for (let input of inputs) {
      try {
        input.focus();
        input.value = command;
        input.dispatchEvent(new Event('input', { bubbles: true }));
        input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
        return true;
      } catch (e) {
        continue;
      }
    }
    return false;
  }
  
  getXTermBuffer(xtermInstance) {
    console.log('[Content] 尝试获取xterm buffer');
    
    try {
      // 使用xterm的buffer API获取内容
      if (xtermInstance.buffer && xtermInstance.buffer.active) {
        console.log('[Content] 使用buffer API');
        const buffer = xtermInstance.buffer.active;
        console.log('[Content] buffer长度:', buffer.length);
        let content = '';
        
        for (let i = 0; i < buffer.length; i++) {
          const line = buffer.getLine(i);
          if (line) {
            const lineText = line.translateToString(true);
            content += lineText + '\n';
          }
        }
        
        console.log('[Content] 获取到buffer内容长度:', content.length);
        return content;
      }
      
      // 备用方案: 使用selection API
      if (xtermInstance.selectAll && xtermInstance.getSelection) {
        console.log('[Content] 使用selection API');
        xtermInstance.selectAll();
        const selection = xtermInstance.getSelection();
        xtermInstance.clearSelection();
        console.log('[Content] 获取到selection内容长度:', selection.length);
        return selection;
      }
      
      console.log('[Content] 无可用的buffer或selection API');
      
    } catch (error) {
      console.log('[Content] 获取xterm buffer失败:', error);
    }
    
    return '';
  }
  
  fallbackDOMMonitor(terminal) {
    console.log('[Content] 使用DOM监听作为备用方案');
    
    // 查找多个可能的输出区域
    const outputAreas = [
      terminal.element.querySelector('.xterm-screen'),
      terminal.element.querySelector('.xterm-viewport'),
      terminal.element.querySelector('.xterm-rows'),
      terminal.element.querySelector('canvas'),
      terminal.element
    ].filter(Boolean);
    
    console.log('[Content] 找到输出区域:', outputAreas.length);
    
    outputAreas.forEach((outputArea, index) => {
      console.log(`[Content] 监控输出区域 ${index}:`, outputArea.tagName, outputArea.className);
      
      const observer = new MutationObserver(() => {
        const currentOutput = this.extractTextFromArea(outputArea);
        if (currentOutput !== terminal.lastOutput) {
          const newContent = currentOutput.slice(terminal.lastOutput.length);
          console.log('[Content] DOM监听检测到变化:', JSON.stringify(newContent));
          terminal.lastOutput = currentOutput;
          this.analyzeOutput(terminal, currentOutput, newContent);
        }
      });

      observer.observe(outputArea, {
        childList: true,
        subtree: true,
        characterData: true,
        attributes: true
      });
    });
    
    // 轮询检查
    setInterval(() => {
      const currentOutput = this.extractTextFromArea(terminal.element);
      if (currentOutput !== terminal.lastOutput) {
        const newContent = currentOutput.slice(terminal.lastOutput.length);
        console.log('[Content] DOM轮询检测到变化:', JSON.stringify(newContent));
        terminal.lastOutput = currentOutput;
        this.analyzeOutput(terminal, currentOutput, newContent);
      }
    }, 1000);
  }
  
  extractTextFromArea(area) {
    // 尝试多种方式提取文本
    if (area.innerText) return area.innerText;
    if (area.textContent) return area.textContent;
    
    // 对于canvas，无法直接获取文本
    if (area.tagName === 'CANVAS') {
      return ''; // canvas内容无法直接读取
    }
    
    return '';
  }

  getKeyCode(char) {
    if (char >= 'a' && char <= 'z') {
      return `Key${char.toUpperCase()}`;
    }
    if (char >= 'A' && char <= 'Z') {
      return `Key${char}`;
    }
    if (char >= '0' && char <= '9') {
      return `Digit${char}`;
    }
    switch (char) {
      case ' ': return 'Space';
      case '-': return 'Minus';
      case '=': return 'Equal';
      case '[': return 'BracketLeft';
      case ']': return 'BracketRight';
      case ';': return 'Semicolon';
      case "'": return 'Quote';
      case ',': return 'Comma';
      case '.': return 'Period';
      case '/': return 'Slash';
      default: return 'Unidentified';
    }
  }

  simulateKeyboardInput(element, text) {
    // 尝试聚焦到可交互元素
    const focusTarget = element.querySelector('[tabindex], input, textarea') || element;
    focusTarget.focus();
    
    // 创建更真实的键盘事件
    const events = ['keydown', 'keypress', 'input', 'keyup'];
    
    // 输入每个字符
    for (let char of text) {
      events.forEach(eventType => {
        const event = new KeyboardEvent(eventType, {
          key: char,
          char: char,
          charCode: char.charCodeAt(0),
          keyCode: char.charCodeAt(0),
          bubbles: true,
          cancelable: true
        });
        focusTarget.dispatchEvent(event);
      });
    }
    
    // 发送回车
    events.forEach(eventType => {
      const enterEvent = new KeyboardEvent(eventType, {
        key: 'Enter',
        keyCode: 13,
        charCode: 13,
        bubbles: true,
        cancelable: true
      });
      focusTarget.dispatchEvent(enterEvent);
    });
  }

  analyzeOutput(terminal, fullOutput, newContent) {
    console.log('[Content] 开始分析输出');
    console.log('[Content] 完整输出:', fullOutput);
    console.log('[Content] 新增内容:', newContent);
    
    const analysis = {
      terminalId: terminal.id,
      fullOutput: fullOutput,
      newContent: newContent,
      timestamp: Date.now(),
      patterns: this.detectPatterns(newContent),
      commandResult: this.parseCommandResult(newContent, terminal.commandHistory),
      nextAction: null
    };

    console.log('[Content] 分析结果:', analysis);

    // 基于输出分析决定下一步操作
    analysis.nextAction = this.determineNextAction(analysis);
    
    if (analysis.nextAction) {
      this.queueCommand(terminal.id, analysis.nextAction);
    }

    // 发送分析结果到sidepanel
    safeSendMessage({
      type: 'OUTPUT_ANALYSIS',
      data: analysis
    });
  }

  detectPatterns(output) {
    const patterns = [];
    
    // 检测常见模式
    if (output.includes('$') || output.includes('#')) {
      patterns.push('SHELL_PROMPT');
    }
    
    if (output.includes('Error') || output.includes('error')) {
      patterns.push('ERROR');
    }
    
    if (output.includes('Permission denied')) {
      patterns.push('PERMISSION_DENIED');
    }
    
    if (output.includes('command not found')) {
      patterns.push('COMMAND_NOT_FOUND');
    }
    
    if (output.includes('Password:') || output.includes('password:')) {
      patterns.push('PASSWORD_PROMPT');
    }

    return patterns;
  }

  parseCommandResult(output, commandHistory) {
    const lastCommand = commandHistory[commandHistory.length - 1];
    if (!lastCommand) return null;
    
    const result = {
      command: lastCommand.command,
      output: output,
      type: 'unknown'
    };
    
    // 根据命令类型解析输出
    if (lastCommand.command.startsWith('ls')) {
      result.type = 'file_list';
      result.files = this.parseFileList(output);
    } else if (lastCommand.command === 'pwd') {
      result.type = 'current_directory';
      result.directory = output.trim();
    } else if (lastCommand.command === 'whoami') {
      result.type = 'current_user';
      result.user = output.trim();
    } else if (lastCommand.command.startsWith('ps')) {
      result.type = 'process_list';
      result.processes = this.parseProcessList(output);
    }
    
    return result;
  }
  
  parseFileList(output) {
    const lines = output.split('\n').filter(line => line.trim());
    const files = [];
    
    lines.forEach(line => {
      // 简单的文件列表解析
      const parts = line.trim().split(/\s+/);
      if (parts.length > 0 && !line.includes('total')) {
        files.push({
          name: parts[parts.length - 1],
          permissions: parts[0],
          size: parts.length > 4 ? parts[4] : null,
          rawLine: line
        });
      }
    });
    
    return files;
  }
  
  parseProcessList(output) {
    const lines = output.split('\n').filter(line => line.trim());
    const processes = [];
    
    lines.forEach((line, index) => {
      if (index === 0) return; // 跳过标题行
      const parts = line.trim().split(/\s+/);
      if (parts.length >= 11) {
        processes.push({
          user: parts[0],
          pid: parts[1],
          cpu: parts[2],
          mem: parts[3],
          command: parts.slice(10).join(' '),
          rawLine: line
        });
      }
    });
    
    return processes;
  }

  determineNextAction(analysis) {
    const { patterns, commandResult } = analysis;
    
    // 根据模式确定下一步操作
    if (patterns.includes('ERROR')) {
      return 'echo "检测到错误，请检查上一个命令"';
    }
    
    if (patterns.includes('COMMAND_NOT_FOUND')) {
      return 'which ls'; // 测试基本命令
    }
    
    if (patterns.includes('PERMISSION_DENIED')) {
      return 'ls -la'; // 检查权限
    }
    
    // 基于命令结果的智能响应
    if (commandResult && commandResult.type === 'file_list') {
      console.log('[Content] 检测到文件列表:', commandResult.files);
    }
    
    return null;
  }

  queueCommand(terminalId, command) {
    this.commandQueue.push({ terminalId, command });
    this.processCommandQueue();
  }

  async processCommandQueue() {
    if (this.isProcessing || this.commandQueue.length === 0) return;
    
    this.isProcessing = true;
    
    while (this.commandQueue.length > 0) {
      const { terminalId, command } = this.commandQueue.shift();
      this.sendCommand(terminalId, command);
      
      // 等待命令执行
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    this.isProcessing = false;
  }

  setupMutationObserver() {
    const observer = new MutationObserver(() => {
      this.detectTerminals();
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  }

  setupMessageListener() {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      switch (request.type) {
        case 'GET_TERMINALS':
          const terminalList = Array.from(this.terminals.entries()).map(([id, terminal]) => ({
            id,
            element: terminal.element.tagName + '.' + terminal.element.className
          }));
          console.log('[Content] 返回终端列表:', terminalList);
          sendResponse(Array.from(this.terminals.keys()));
          break;
          
        case 'SEND_COMMAND':
          console.log('[Content] 收到SEND_COMMAND消息:', request);
          this.sendCommand(request.terminalId, request.command).then(success => {
            console.log('[Content] 命令执行结果:', success);
            sendResponse({ success });
          });
          return true; // 保持消息通道开放
          break;
          
        case 'GET_TERMINAL_INFO':
          const terminal = this.terminals.get(request.terminalId);
          sendResponse(terminal ? {
            id: terminal.id,
            lastOutput: terminal.lastOutput,
            commandHistory: terminal.commandHistory
          } : null);
          break;
      }
    });
  }

  /**
   * 拦截xterm.js构造函数 - 用于输出监控
   * 这个方法拦截Terminal构造函数，在xterm实例创建时自动开始监控其输出
   * 主要用于获取终端的buffer内容变化，不影响命令发送功能
   * 
   * 与interceptWebSocket的区别：
   * - interceptXTerm: 监控xterm实例的buffer变化（客户端渲染层面）
   * - interceptWebSocket: 监控WebSocket数据流（网络传输层面）
   * 
   * 两者互补，提供不同层面的数据监控
   */
  interceptXTerm() {
    console.log('[Content] 设置xterm拦截用于输出监控');
    
    // 拦截全局Terminal构造函数
    if (window.Terminal) {
      console.log('[Content] 找到Terminal构造函数');
      const OriginalTerminal = window.Terminal;
      const self = this;
      
      window.Terminal = function(...args) {
        console.log('[Content] 拦截到Terminal构造调用');
        const instance = new OriginalTerminal(...args);
        
        // 存储实例引用仅用于监控输出，不用于发送命令
        if (!window._xtermInstancesForMonitoring) {
          window._xtermInstancesForMonitoring = [];
        }
        window._xtermInstancesForMonitoring.push(instance);
        console.log('[Content] 捕获到xterm实例用于监控:', instance);
        
        // 拦截open方法，在终端打开时开始监控
        const originalOpen = instance.open;
        instance.open = function(element) {
          console.log('[Content] xterm.open被调用，开始监控:', element);
          const result = originalOpen.call(this, element);
          
          // 将实例与DOM元素关联，仅用于输出监控
          element._xtermInstanceForMonitoring = instance;
          
          // 开始监听终端输出变化
          self.startOutputMonitoring(instance, element);
          
          return result;
        };
        
        return instance;
      };
      
      // 保持原型链不变
      window.Terminal.prototype = OriginalTerminal.prototype;
    }
    
    // 检查其他可能的xterm导入方式（如xterm.Terminal）
    const checkForXTerm = () => {
      if (window.xterm && window.xterm.Terminal) {
        console.log('[Content] 找到xterm.Terminal');
        this.interceptXTermNamespace(window.xterm);
      }
    };
    
    // 延迟检查，确保xterm库已加载
    checkForXTerm();
    setTimeout(checkForXTerm, 1000);
    setTimeout(checkForXTerm, 3000);
  }
  
  interceptXTermNamespace(xterm) {
    const OriginalTerminal = xterm.Terminal;
    const self = this;
    
    xterm.Terminal = function(...args) {
      console.log('[Content] 拦截到xterm.Terminal构造调用');
      const instance = new OriginalTerminal(...args);
      
      if (!window._xtermInstancesForMonitoring) {
        window._xtermInstancesForMonitoring = [];
      }
      window._xtermInstancesForMonitoring.push(instance);
      console.log('[Content] 捕获到xterm实例用于监控:', instance);
      
      const originalOpen = instance.open;
      instance.open = function(element) {
        console.log('[Content] xterm.open被调用，开始监控:', element);
        const result = originalOpen.call(this, element);
        element._xtermInstanceForMonitoring = instance;
        self.startOutputMonitoring(instance, element);
        return result;
      };
      
      return instance;
    };
    
    xterm.Terminal.prototype = OriginalTerminal.prototype;
  }
  
  startOutputMonitoring(instance, element) {
    console.log('[Content] 开始监控拦截到的xterm实例输出');
    
    let lastContent = '';
    
    // 监听写入事件
    if (instance.onWriteParsed) {
      instance.onWriteParsed(() => {
        console.log('[Content] 拦截 - xterm onWriteParsed触发');
        const content = this.getXTermBuffer(instance);
        if (content !== lastContent) {
          const newContent = content.slice(lastContent.length);
          console.log('[Content] 拦截 - 检测到输出变化:', JSON.stringify(newContent));
          lastContent = content;
          
          // 发送分析结果
          this.analyzeInterceptedOutput(newContent, content);
        }
      });
    }
    
    // 轮询检查
    setInterval(() => {
      const content = this.getXTermBuffer(instance);
      if (content && content !== lastContent) {
        const newContent = content.slice(lastContent.length);
        console.log('[Content] 拦截 - 轮询检测到输出变化:', JSON.stringify(newContent));
        lastContent = content;
        
        // 发送分析结果
        this.analyzeInterceptedOutput(newContent, content);
      }
    }, 1000);
  }
  
  analyzeInterceptedOutput(newContent, fullContent) {
    const analysis = {
      terminalId: 'intercepted',
      fullOutput: fullContent,
      newContent: newContent,
      timestamp: Date.now(),
      patterns: this.detectPatterns(newContent),
      commandResult: this.parseCommandResult(newContent, []),
      nextAction: null
    };

    console.log('[Content] 拦截分析结果:', analysis);

    // 发送分析结果到sidepanel
    safeSendMessage({
      type: 'OUTPUT_ANALYSIS',
      data: analysis
    });
  }
  
  // WebSocket拦截已在文件开头立即执行，这里不需要重复实现
  
  handleMessageData(data) {
    if (!data || typeof data !== 'string') return '[Invalid Data]';
    
    try {
      const messageType = data[0];
      const payload = data.slice(1);
      
      switch (messageType) {
        case '1': // 终端输出
          const decoded = atob(payload);
          const bytes = Uint8Array.from(decoded, c => c.charCodeAt(0));
          const text = new TextDecoder('utf-8').decode(bytes);
          console.log('[Content] 解析终端输出:', text);
          return text;
        case '2':
        case '3':
        case '4':
          return `[Control Message Type ${messageType}]`;
        case '5':
          return '[Connection Close]';
        default:
          // 可能是JSON登录数据
          try {
            const jsonData = JSON.parse(data);
            return `[Login Data: ${JSON.stringify(jsonData)}]`;
          } catch {
            return data;
          }
      }
    } catch (error) {
      console.log('[Content] 解析消息失败:', error);
      return data;
    }
  }

  analyzeWebSocketData(data) {
    // 过滤控制字符和空数据
    if (!data || data.length === 0) return;
    
    // 移除ANSI转义序列和控制字符
    const cleanData = data.replace(/\x1b\[[0-9;]*[mGKH]/g, '').replace(/[\x00-\x1f\x7f]/g, '');
    
    if (cleanData.trim().length === 0) return;
    
    const analysis = {
      terminalId: 'websocket',
      fullOutput: cleanData,
      newContent: cleanData,
      timestamp: Date.now(),
      patterns: this.detectPatterns(cleanData),
      type: 'websocket_output',
      rawData: data // 保留原始数据
    };
    
    console.log('[Content] WebSocket数据分析:', {
      清理后: cleanData.substring(0, 100),
      模式: analysis.patterns,
      原始数据长度: data.length
    });
    
    // 只分析有意义的数据
    if (analysis.patterns.length > 0 || cleanData.includes('$') || cleanData.includes('#')) {
      safeSendMessage({
        type: 'OUTPUT_ANALYSIS',
        data: analysis
      });
    }
  }

  handleInterceptedMessage(url, data) {
    try {
      const message = typeof data === 'string' ? data : new TextDecoder().decode(data);
      console.log('[Content] 处理拦截的消息:', message.substring(0, 100));
      
      safeSendMessage({
        type: 'WEBSOCKET_DATA',
        data: {
          url: url,
          message: message,
          timestamp: Date.now()
        }
      });
      
      const parsedMessage = this.handleMessageData(message);
      this.analyzeWebSocketData(parsedMessage);
    } catch (error) {
      console.log('[Content] 处理拦截消息失败:', error);
    }
  }
  
  handleInterceptedSend(url, data) {
    try {
      const message = typeof data === 'string' ? data : new TextDecoder().decode(data);
      console.log('[Content] 处理拦截的发送:', message.substring(0, 100));
      
      safeSendMessage({
        type: 'WEBSOCKET_SEND',
        data: {
          url: url,
          message: message,
          timestamp: Date.now()
        }
      });
    } catch (error) {
      console.log('[Content] 处理拦截发送失败:', error);
    }
  }

  checkInterceptionStatus() {
    console.log('[Content] 检查注入脚本拦截状态');
    
    // 延迟检查，等待注入脚本加载
    setTimeout(() => {
      console.log('[Content] 检查WebSocket是否被注入脚本修改');
      
      // 检查注入脚本是否成功修改了WebSocket
      const wsString = window.WebSocket.toString();
      const isIntercepted = wsString.includes('WebSocket被创建') || window._webSocketIntercepted;
      
      console.log('[Content] WebSocket是否被拦截:', isIntercepted);
      console.log('[Content] WebSocket函数内容:', wsString.substring(0, 200));
      
      if (isIntercepted) {
        console.log('[Content] ✓ WebSocket拦截成功设置');
      } else {
        console.log('[Content] ✗ WebSocket拦截设置失败');
      }
    }, 1000);
  }

  generateTerminalId(element) {
    return `terminal_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}



// 初始化控制器
const xtermController = new XTermController();
window.xtermController = xtermController;